package com.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory factory;//全局变量
    static {
        //获取mybatis全局文件输入流
        InputStream in= null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
            //创建SqlSessionFactory对象
            factory=new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //创建SqlSession对象
    public static SqlSession createSqlSession(){
        return factory.openSession(false);//关闭自动提交事务
    }
    //关闭SqlSession对象
    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}
